import 'package:flutter/material.dart';
import '../services/alger_api_service.dart';
import 'alger_playlist_detail_screen.dart';

class AlgerToplistScreen extends StatefulWidget {
  const AlgerToplistScreen({super.key});

  @override
  State<AlgerToplistScreen> createState() => _AlgerToplistScreenState();
}

class _AlgerToplistScreenState extends State<AlgerToplistScreen> {
  final AlgerApiService _api = AlgerApiService();
  List<AlgerPlaylist> _toplists = [];
  bool _loading = true;

  @override
  void initState() {
    super.initState();
    _loadToplists();
  }

  Future<void> _loadToplists() async {
    setState(() => _loading = true);
    try {
      final list = await _api.fetchToplists();
      setState(() => _toplists = list);
    } catch (e) {
      debugPrint('加载排行榜列表失败: $e');
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('加载排行榜列表失败: $e')),
        );
      }
    } finally {
      if (mounted) setState(() => _loading = false);
    }
  }

  @override
  Widget build(BuildContext context) {
    final isWide = MediaQuery.of(context).size.width > 900;
    final crossAxisCount = isWide ? 5 : 2;
    final spacing = 12.0;
    final childAspectRatio = isWide ? 0.70 : 0.66;

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const SizedBox(height: 8),
        Padding(
          padding: const EdgeInsets.symmetric(horizontal: 16),
          child: Row(
            children: [
              const Icon(Icons.bar_chart, size: 18, color: Colors.black54),
              const SizedBox(width: 6),
              Text(
                '官方排行榜',
                style: Theme.of(context).textTheme.titleMedium?.copyWith(fontWeight: FontWeight.w600),
              ),
              const Spacer(),
              IconButton(
                tooltip: '刷新',
                onPressed: _loadToplists,
                icon: const Icon(Icons.refresh, size: 18),
              ),
            ],
          ),
        ),
        const SizedBox(height: 8),
        _loading
            ? const Center(child: CircularProgressIndicator())
            : GridView.builder(
                shrinkWrap: true,
                physics: const NeverScrollableScrollPhysics(),
                padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: crossAxisCount,
                  mainAxisSpacing: spacing,
                  crossAxisSpacing: spacing,
                  childAspectRatio: childAspectRatio,
                ),
                itemCount: _toplists.length,
                itemBuilder: (context, index) {
                  final p = _toplists[index];
                  return GestureDetector(
                    onTap: () {
                      Navigator.of(context).push(
                        MaterialPageRoute(
                          builder: (_) => AlgerPlaylistDetailScreen(
                            playlistId: p.id,
                            playlistName: p.name,
                            coverImgUrl: p.coverImgUrl,
                          ),
                        ),
                      );
                    },
                    child: Container(
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(12),
                        border: Border.all(color: Colors.grey[300]!),
                        color: Colors.white,
                      ),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          ClipRRect(
                            borderRadius: const BorderRadius.only(
                              topLeft: Radius.circular(12),
                              topRight: Radius.circular(12),
                            ),
                            child: AspectRatio(
                              aspectRatio: 1,
                              child: p.coverImgUrl.isNotEmpty
                                  ? Image.network(p.coverImgUrl, fit: BoxFit.cover)
                                  : Container(color: Colors.grey[200]),
                            ),
                          ),
                          Padding(
                            padding: const EdgeInsets.fromLTRB(8, 8, 8, 10),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text(
                                  p.name,
                                  maxLines: 2,
                                  overflow: TextOverflow.ellipsis,
                                  softWrap: true,
                                  style: const TextStyle(
                                    fontSize: 13,
                                    fontWeight: FontWeight.w600,
                                    color: Colors.black87,
                                  ),
                                ),
                                const SizedBox(height: 4),
                                if ((p.updateFrequency ?? '').isNotEmpty)
                                  Row(
                                    children: [
                                      const Icon(Icons.schedule, size: 14, color: Colors.black45),
                                      const SizedBox(width: 4),
                                      Text(
                                        p.updateFrequency!,
                                        maxLines: 1,
                                        overflow: TextOverflow.ellipsis,
                                        style: const TextStyle(
                                          fontSize: 11,
                                          color: Colors.black54,
                                        ),
                                      ),
                                    ],
                                  ),
                              ],
                            ),
                          ),
                        ],
                      ),
                    ),
                  );
                },
              ),
      ],
    );
  }
}
